const api = require('../../utils/api.js');

Page({
  data: {
    selectedTab: 'all',
    historyList: [],
    filteredList: []
  },

  onLoad() {
    this.fetchHistory();
  },

  async fetchHistory() {
    try {
      const res = await api.request({
        url: '/api/assessment/records',
        method: 'GET',
        data: { page: 1, per_page: 50 }
      });
      if (res.code === 200 && Array.isArray(res.data)) {
        const list = res.data
          .filter(item => ['MBTI', 'SAS', 'SDS'].includes(item.assessment_name))
          .map(item => ({
            id: item.id,
            type: item.assessment_name,
            time: this.formatTime(item.assessment_time),
            // MBTI
            mbtiType: item.assessment_name === 'MBTI' ? (item.results.mbti_type || '') : '',
            // SAS/SDS
            score: item.assessment_name === 'SAS' ? item.results.standard_score
                  : item.assessment_name === 'SDS' ? item.results.standard_score
                  : '',
            scoreLevel: this.getScoreLevel(item.assessment_name, item.results.standard_score),
            result: item.assessment_name === 'MBTI'
              ? item.results.description
              : item.results.interpretation
          }));
        this.setData({
          historyList: list
        });
        this.filterList(this.data.selectedTab, list);
      } else {
        this.setData({ historyList: [], filteredList: [] });
      }
    } catch (e) {
      wx.showToast({ title: '获取历史失败', icon: 'none' });
      this.setData({ historyList: [], filteredList: [] });
    }
  },

  onTabChange(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({ selectedTab: tab });
    this.filterList(tab, this.data.historyList);
  },

  filterList(tab, list) {
    let filtered = [];
    if (tab === 'all') {
      filtered = list;
    } else {
      filtered = list.filter(item => item.type === tab);
    }
    this.setData({ filteredList: filtered });
  },

  getScoreLevel(type, score) {
    if (type === 'SAS') {
      if (score < 50) return 'normal';
      if (score < 60) return 'mild';
      return 'severe';
    }
    if (type === 'SDS') {
      if (score < 53) return 'normal';
      if (score < 63) return 'mild';
      return 'severe';
    }
    return '';
  },

  formatTime(ts) {
    const date = new Date(ts);
    return `${date.getFullYear()}年${date.getMonth()+1}月${date.getDate()}日 ${date.getHours().toString().padStart(2,'0')}:${date.getMinutes().toString().padStart(2,'0')}`;
  },

  goBack() {
    wx.navigateBack();
  }
});